using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.DeviceDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.DeviceDictionaryHandler
{
    /// <summary>
    /// 删除设备处理器
    /// </summary>
    public class DeleteEquipmentHandler : IRequestHandler<DeleteEquipmentCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Equipment> _equipmentRepository;
        private readonly ILogger<DeleteEquipmentHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DeleteEquipmentHandler(
            IBaseRepository<Equipment> equipmentRepository,
            ILogger<DeleteEquipmentHandler> logger)
        {
            _equipmentRepository = equipmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除请求
        /// </summary>
        public Task<ApiResult<bool>> Handle(DeleteEquipmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var equipment = _equipmentRepository.GetModel(request.Id);
                if (equipment == null)
                {
                    return Task.FromResult(new ApiResult<bool>
                    {
                        Code = ApiEnums.NotFound,
                        Msg = "设备不存在",
                        Data = false
                    });
                }

                // 逻辑删除
                equipment.IsDeleted = true;
                var result = _equipmentRepository.Update(equipment);

                return Task.FromResult(new ApiResult<bool>
                {
                    Code = result > 0 ? ApiEnums.Success : ApiEnums.Error,
                    Msg = result > 0 ? "设备删除成功" : "设备删除失败",
                    Data = result > 0
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除设备时发生异常");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Error,
                    Msg = "删除设备时发生错误",
                    Data = false
                });
            }
        }
    }
}